package com.wlyy.bcwlw.common.export2excel.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.wlyy.bcwlw.common.export2excel.inter.ICellValueSetter;
import com.wlyy.bcwlw.common.utils.ExcelUtil;

public class ImageCellValueSetter implements ICellValueSetter {
	
	public static final ImageCellValueSetter INSTANCE = new ImageCellValueSetter();

	@Override
	public void setCellValue(HSSFWorkbook wb, HSSFSheet sheet, HSSFCell cell,
			Object value) {
		// TODO Auto-generated method stub
		if(value instanceof File){
			if(((File) value).exists()){
				ExcelUtil.setText(cell, "文件不存在");
				return ;
			}
			HSSFPatriarch patriarch =sheet.createDrawingPatriarch();
			ByteArrayOutputStream byteArrayout = new ByteArrayOutputStream();
			BufferedImage imge;
			try{
				imge = ImageIO.read((File)value);
				ImageIO.write(imge, "jpg", byteArrayout);
				
				HSSFClientAnchor anchor = new HSSFClientAnchor(4, 2, 
						800, 255, 
						cell.getCellNum(), cell.getRowIndex(), 
						cell.getCellNum(), cell.getRowIndex());
				anchor.setAnchorType(2);
				patriarch.createPicture(anchor,  wb.addPicture(byteArrayout.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
				sheet.getRow(cell.getRowIndex()).setHeight((short)imge.getHeight());
			} catch (IOException e){
				ExcelUtil.setText(cell, "读取文件失败");
			}
		}
		
	}
	

}
